package application.common.plugins.serialPort;

import java.io.*;
import java.util.*;
import com.jfinal.kit.StrKit;
import application.common.model.Cabinet;
import gnu.io.*;

public class SerialCommunication{

	private Enumeration<?> portList;
	private CommPortIdentifier commPortIdentifier; 
	private InputStream inputStream;
	private OutputStream outputStream;
	private SerialPort serialPort;
	private Cabinet cabinet;
	private SerialPortEventListener serialPortEventListener;

	public SerialCommunication(Cabinet cabinet,SerialPortEventListener serialPortEventListener) {
		this.cabinet = cabinet;
		this.serialPortEventListener = serialPortEventListener;
	}

	public boolean startComPort() {
		try {
			portList = CommPortIdentifier.getPortIdentifiers();
			while (portList.hasMoreElements()) {
				commPortIdentifier = (CommPortIdentifier) portList.nextElement();
				// 判断端口类型是否为串口
				if (commPortIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) {
					if (StrKit.equals(commPortIdentifier.getName(), "COM" + cabinet.getComPort())) {
						try {
							serialPort = (SerialPort) commPortIdentifier.open(cabinet.getId(), 2000);
						} catch (PortInUseException e) {
							e.printStackTrace();
							return false;
						}
						try {
							inputStream = serialPort.getInputStream();
							outputStream = serialPort.getOutputStream();
						} catch (IOException e) {
							return false;
						}

						try {
							if(serialPortEventListener!=null)
								serialPort.addEventListener(serialPortEventListener);
						} catch (TooManyListenersException e) {
							e.printStackTrace();
							return false;
						}
						serialPort.notifyOnDataAvailable(true);
						try {
							serialPort.setSerialPortParams(cabinet.getBaudRate(),SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
							return true;
						} catch (UnsupportedCommOperationException e) {
							return false;
						}
					}
				}
			}
		}catch (Exception e) {
		}
		return false;
	}

	public boolean sendCMD(byte[] cmd) {
		try {
			outputStream.write(cmd, 0,cmd.length);
			outputStream.flush();
			return true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public void release() {
		if (serialPort != null) {
			serialPort.close();
		}
		if (inputStream != null) {
			try {
				inputStream.close();
			} catch (IOException e) {
			}
		}
		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (IOException e) {
			}
		}
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public OutputStream getOutputStream() {
		return outputStream;
	}

	public void setOutputStream(OutputStream outputStream) {
		this.outputStream = outputStream;
	}

}